package com.stc.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.stc.pojo.Order;
import com.stc.utilities.DatabaseAdapter;

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ShowAndReadActivity extends ListActivity implements
		TextToSpeech.OnInitListener {

	DatabaseAdapter myDBAdapter;
	private TextToSpeech mTts;
	private TextView orderTitle;
	private String race = "";
	private String strategyName = "";
	private String strategyId = "";
	private ListView ordersListView;
	Cursor ordersCursor;
	TextToSpeech texttospeech;
	
	static final ArrayList<HashMap<String, String>> orders = new ArrayList<HashMap<String, String>>();

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_read_activity);
		
		Log.d("this: ", this.toString());
		
		texttospeech = new TextToSpeech(this, this);
		
		myDBAdapter = DatabaseAdapter.getHelper(getApplicationContext());

		orderTitle = (TextView) findViewById(R.id.titleListOrders);
		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			race = extras.getString("race");
			strategyName = extras.getString("strategyName");
			strategyId = extras.getString("strategyId");

			System.out.println("strategyId: " + strategyId);
		}

		orderTitle.setText("Race " + race + ", tactics " + strategyName);
		Log.d("tacticsTitle.getText(): ", String.valueOf(orderTitle.getText()));

		ordersListView = (ListView) findViewById(android.R.id.list);

		// uzupelnienie listy
		
		
		
	}

	private void fillOrdersList() {

		Log.d("strategyId", String.valueOf(strategyId));

		ordersCursor = myDBAdapter.getOrdersByTacticsId(Long
				.valueOf(strategyId));

		Log.d("cursor", String.valueOf(ordersCursor.getCount()));

		startManagingCursor(ordersCursor);
		updateOrdersList();
	}

	private void updateOrdersList() {
		ordersCursor.requery();

		orders.clear();

		if (ordersCursor.moveToFirst()) {
			do {
				String order = ordersCursor.getString(ordersCursor
						.getColumnIndex(DatabaseAdapter.KEY_COMMAND));
				String time = ordersCursor.getString(ordersCursor
						.getColumnIndex(DatabaseAdapter.KEY_TIME));
				HashMap<String, String> ordersTemp = new HashMap<String, String>();
				ordersTemp.put("orderName", order);
				ordersTemp.put("orderTime", time);
				orders.add(ordersTemp);
			} while (ordersCursor.moveToNext());
		}
	}

	private void fillListView() {
		// List<String> shortcuts = new ArrayList<String>();
		// for(Tactics tactic : tactics)
		// shortcuts.add(tactic.getTactic());
		// ArrayAdapter<String> adapter = new
		// ArrayAdapter<String>(getApplicationContext(),
		// android.R.layout.simple_list_item_1, shortcuts);
		// tacticsListView.setAdapter(adapter);

		Log.d("ordersListView", String.valueOf(ordersListView));

		SimpleAdapter simpleAdapter = new SimpleAdapter(this, orders,
				R.layout.custom_row_order, new String[] { "orderName",
						"orderTime" }, new int[] { R.id.orderName,
						R.id.orderTime });
		setListAdapter(simpleAdapter);
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// get the bundle and extract data by key

				Bundle b = msg.getData();
				String key = b.getString("key");
				Toast.makeText(getApplicationContext(), "You selected: " + key, Toast.LENGTH_SHORT).show();
				Log.d("TEKST: ", key);
				texttospeech.speak(key, TextToSpeech.QUEUE_FLUSH, null);
		}
	};

	protected void onStart() {
		super.onStart();


		// create a new thread
		Thread background = new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < orders.size(); i++) {
					try {
						HashMap<String, String> order = orders.get(i);
						int oldTime = 0;
						if( i > 0 ){
							HashMap<String, String> orderOld = orders.get(i-1);
							oldTime = parseTime(orderOld.get("orderTime"));
						}
						int newTime = parseTime(order.get("orderTime"));
						
						Thread.sleep((newTime-oldTime)*1000);
						Message msg = new Message();
						Bundle b = new Bundle();
						b.putString("key", order.get("orderName"));
						Log.d("TEKST: ", "tutaj");
						msg.setData(b);
						// send message to the handler with the current message
						// handler

						handler.sendMessage(msg);
					} catch (Exception e) {
						Log.e("Error", e.toString());
					}
				}
			}
		});

		background.start();
	}
	
	
	 private int parseTime(String s)
	    {
	        String as[] = s.split(":");
	        int i = Integer.parseInt(as[0].trim());
	        int j = Integer.parseInt(as[1].trim());
	        return i * 60 + j;
	    } 
	
	 @Override
		public void onDestroy() {
			// Don't forget to shutdown!
			if (texttospeech != null) {
				texttospeech.stop();
				texttospeech.shutdown();
			}
			myDBAdapter.close();
			super.onDestroy();
		}

		@Override
		public void onInit(int status) {
			 if (status == TextToSpeech.SUCCESS) {
				 Log.d("ONINIT: ", "ready");
				 fillOrdersList();
				 fillListView();
				 onStart();
			 }

		}

	/*
	 * InputStream inputStream =
	 * getResources().openRawResource(R.raw.protosattack); InputStreamReader
	 * inputStreamReader = new InputStreamReader(inputStream); BufferedReader
	 * bufferedReader = new BufferedReader(inputStreamReader); String line = "";
	 * String s12 = ""; try { line = bufferedReader.readLine(); StringBuilder
	 * stringbuilder = new StringBuilder(); StringBuilder stringbuilder1 =
	 * stringbuilder.append(line);
	 * 
	 * inputStream.close(); inputStreamReader.close(); bufferedReader.close();
	 * s12 = stringbuilder.toString(); System.out.println("s12: "+s12);
	 * 
	 * } catch (IOException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } JSONObject jsonobject; int k = 0; try { jsonobject
	 * = new JSONObject(s12); JSONArray jsonarray =
	 * jsonobject.getJSONArray("items"); JSONObject jsonobject1 =
	 * jsonarray.getJSONObject(k); String s = jsonobject1.getString("name");
	 * String s1 = jsonobject1.optString("shortDesc");
	 * 
	 * long l = jsonobject1.getInt("id"); System.out.println("id = "+l); double
	 * d = jsonobject1.optDouble("rating", 0D);
	 * System.out.println("rating = "+d); String s2 =
	 * jsonobject1.optString("submittedBy");
	 * System.out.println("submittedBy = "+s2); long l1 =
	 * jsonobject1.getLong("timestamp"); Date date = new Date(l1);
	 * System.out.println("date = "+date); //buildorder.setTimestamp(date);
	 * String s3 = jsonobject1.optString("longdesc");
	 * System.out.println("longdesc = "+s3); String s4 =
	 * jsonobject1.optString("bestAgainst");
	 * System.out.println("bestAgainst = "+s4);
	 * 
	 * JSONArray jsonarray1 = jsonobject1.getJSONArray("items");
	 * 
	 * //String[][] orderList = new String[jsonarray1.length()][2]; String[]
	 * orderList = new String[jsonarray1.length()];
	 * 
	 * int i = 0; do { int j = jsonarray1.length(); System.out.println("j: "+j);
	 * if (i >= j) { break; } JSONObject jsonobject2 =
	 * jsonarray1.getJSONObject(i); String s5 = jsonobject2.getString("name");
	 * System.out.println("name: "+s5); int sup = jsonobject2.getInt("supply");
	 * double d1 = jsonobject2.getDouble("time"); //orderList[i][0] =
	 * String.valueOf(d1); //orderList[i][1] = String.valueOf(s5); orderList[i]
	 * = String.valueOf(s5); i++; } while (true);
	 * 
	 * 
	 * setListAdapter(new ArrayAdapter<Object>(this,
	 * android.R.layout.simple_list_item_1, orderList));
	 * 
	 * 
	 * for(int z=0;z<orderList.length;z++) speak(orderList[z]);
	 * 
	 * } catch (JSONException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); }
	 * 
	 * }
	 */

	


}
